package com.zjitc.serviceoss.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.zjitc.common.exception.AuthException;
import com.zjitc.serviceoss.service.IOssService;
import com.zjitc.serviceoss.utils.ReadOssProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssService implements IOssService {

    @Override
    public String uploadImg(MultipartFile file, String cateDir) {

        // 读取出准备的属性
        String endPoint = ReadOssProperties.END_POINT;
        String bucketName = ReadOssProperties.BUCKET_NAME;
        String keyId = ReadOssProperties.KEY_ID;
        String keySecret = ReadOssProperties.KEY_SECRET;
        // 图片地址
        String url = "";

        // 创建OSS对象
        OSSClient ossClient = new OSSClient(endPoint, keyId, keySecret);

        // 判断桶是否存在，不存在则创建
        if(!ossClient.doesBucketExist(bucketName)) {
            ossClient.createBucket(bucketName);
            //设置桶权限
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }

        try {
            // 获取上次文件流
            InputStream inputStream = file.getInputStream();

            // 处理文件名
            // 随机生成文名称 (避免保存图片名称冲突)
            String randomFileName = UUID.randomUUID().toString();

            // 取出传递文件的后缀名
            // 获取整个传递过来的文件名 test.png
            String fileName = file.getOriginalFilename();
            // 取出 . 的索引值
            int index = fileName.lastIndexOf(".");
            // 截取字符串 .png
            String suffix = fileName.substring(index);

            // 拼接随机名称 + 取出传递文件的后缀名；
            String overName = cateDir + "/" + randomFileName + suffix;

            // 文件上传至阿里云服务器
            ossClient.putObject(bucketName, overName, inputStream);

            // 关闭OSS对象
            ossClient.shutdown();

            // 拼接图片地址
            url = "https://" + bucketName + "." + endPoint + "/" + overName;

        } catch (IOException e) {
            throw new AuthException("上传文件失败，请联系管理员！");
        }
        // 返回图片地址给前端
        return url;
    }
}
